<template>
  <div class="weather-city">
    <div class="weather-header">
      <nav class="container">
        <a href="/">
          <div class="title">
            <font-awesome-icon icon="fa-solid fa-sun" />
            <span>新中地天气</span>
          </div>
        </a>
        <div class="city">
          <h4>{{ currentCity }}</h4>
          <span>实时天气: {{ currentWeather.condition }}{{ currentWeather.temp }}℃</span>
          <span>{{ currentWeather.windDir }}风{{currentWeather.windLevel}}级</span>
        </div>
        <div class="icon">
          <font-awesome-icon
            icon="fa-solid fa-circle-info"
            @click="toggleInfo"
          />
          <font-awesome-icon
            icon="fa-solid fa-plus"
            @click="saveCurrentCity"
            v-if="showSaveBtn"
          />
        </div>
      </nav>
      <div
        class="backdrop"
        :class="{ active: showHelp }"
        @click="toggleInfo"
      ></div>
      <div class="info-card" :class="showHelp ? 'is-show' : ''">
        <h2>关于:</h2>
        <p>这个应用可以用来追踪你选择城市的当前天气</p>
        <h2>如何使用:</h2>
        <p>
          1.点击搜索框输入你希望追踪的城市<br />
          2.在搜索结果中选中一个城市，你将获取当地最新的天气<br />
          3.点击右侧的＋号可以将追踪城市的天气情况保存在首页
        </p>
        <h2>移除城市:</h2>
        <p>如果你不想在首页关注某个城市,可以通过底部的按钮删除它</p>
        <button @click="toggleInfo">关闭</button>
      </div>
    </div>
    <div class="text">
      你正在预览{{ currentCity }}的天气信息
      <span v-if="showSaveBtn">，可以通过右上角的"+"号按钮保存起来</span>
    </div>
    <div class="weather-today">
      <div>当日气温是：{{ currentWeather.temp }}摄氏度</div>
      <div>当日天气是：{{ currentWeather.condition }}</div>
      <div>当日风向是：{{ currentWeather.windDir }}</div>
      <div>当日风力是：{{ currentWeather.windLevel }}级</div>
    </div>
    <hr />
    <div class="weather-container">
      <div class="weather-content">
        <div class="weather-days">
          <div class="weather-day" v-for="day in forecastList" :key="day.date">
            <span>{{ day.week }}</span>
            <span>{{ day.date }}</span>
            <span>{{ day.condition }}</span>
            <span>{{ day.windLevel }}级</span>
          </div>
        </div>
        <div class="weather-chart">
          <v-chart :option="option"></v-chart>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getWeatherData, getWeatherPredictionData } from '@/api'

const route = useRoute()

const currentCity = ref('')
const currentWeather = ref({
  temp: '',
  condition: '',
  windDir: '',
  windLevel: '',
})
const forecastList = ref([])
const savedCities = ref([])
const showSaveBtn = ref(true)
const showHelp = ref(false)
const option = ref({})
const key = ref('e05b2f8dddd45367d027e8f1792cc710')

// 初始化星期
const initWeek = (weekNum) => {
  const week = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    7: '周日',
  }
  return week[weekNum]
}

const renderChart = (dayTemps, nightTemps) => {
  option.value = {
    xAxis: {
      type: 'category',
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      show: false,
      axisLabel: {
        formatter: '{value} °C',
      },
      scale: true,
    },
    grid: {
      top: '20%',
      left: '7%',
      right: '10%',
      bottom: '20%',
      containLabel: true,
    },
    series: [
      {
        name: '白天气温',
        type: 'line',
        data: dayTemps,
        smooth: true,
        label: {
          show: true,
          formatter: function (params) {
            return `白${params.value}℃`
          },
          position: 'top',
          textStyle: {
            fontSize: 10,
            color: 'white',
          },
        },
      },
      {
        name: '夜晚气温',
        type: 'line',
        data: nightTemps,
        smooth: true,
        label: {
          show: true,
          formatter: function (params) {
            return `晚${params.value}℃`
          },
          position: 'bottom',
          textStyle: {
            fontSize: 10,
            color: 'white',
          },
        },
      },
    ],
  }
}

// 已保存城市
const loadSavedCities = () => {
  const saved = localStorage.getItem('savedWeatherCities')
  savedCities.value = saved ? JSON.parse(saved) : []
  checkIfSaved()
}

// 检查当前城市是否保存
const checkIfSaved = () => {
  const isSaved = savedCities.value.some(
    (city) => city.adcode === route.params.adcode
  )
  showSaveBtn.value = !isSaved
}

// 保存当前城市
const saveCurrentCity = () => {
  const newCity = {
    adcode: route.params.adcode,
    name: currentCity.value,
    temp: currentWeather.value.temp,
  }
  savedCities.value.push(newCity)
  showSaveBtn.value = false
}

// 提示框
const toggleInfo = () => {
  showHelp.value = !showHelp.value
}

// 初始化数据
const initData = async () => {
  const currentRes = await getWeatherData(route.params.adcode, key.value)
  const currentData = currentRes.lives[0]
  currentCity.value = currentData.city
  currentWeather.value = {
    temp: currentData.temperature,
    condition: currentData.weather,
    windDir: currentData.winddirection,
    windLevel: currentData.windpower,
  }

  const forecastRes = await getWeatherPredictionData(
    route.params.adcode,
    key.value
  )
  const forecasts = forecastRes.forecasts[0].casts
  const dayTemps = []
  const nightTemps = []

  forecastList.value = forecasts.map((item, index) => {
    const week =
      index === 0 ? '今天' : index === 1 ? '明天' : initWeek(item.week)
    dayTemps.push(item.daytemp)
    nightTemps.push(item.nighttemp)

    return {
      week,
      date: item.date.slice(5),
      condition: item.dayweather,
      windLevel: item.daypower,
    }
  })
  renderChart(dayTemps, nightTemps)
}

// 监听保存城市变化
watch(
  savedCities,
  () => {
    localStorage.setItem(
      'savedWeatherCities',
      JSON.stringify(savedCities.value)
    )
  },
  { deep: true }
)

onMounted(() => {
  loadSavedCities()
  initData()
})
</script>

<style lang="scss" scoped>
.weather-city {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;

  .weather-header {
    position: sticky;
    top: 0;
    width: 100vw;
    height: 80px;
    background-color: #00668a;
    color: white;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1),
      0 4px 6px -4px rgb(0 0 0 / 0.1);
    z-index: 10;

    .container {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto;
      padding: 24px 160px;
      gap: 16px;
      height: 100%;
      max-width: 1280px;
      font-weight: 600;

      a {
        color: white;
        text-decoration: none;

        .title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 24px;
        }
      }

      .city {
        display: flex;
        flex: 1;
        align-items: center;
        gap: 16px;

        h4 {
          font-size: 18px;
          font-weight: 400;
          margin: 0;
        }

        span {
          font-size: 14px;
          font-weight: 400;
        }
      }

      .icon {
        flex: 1 1 0%;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        font-size: 20px;
        cursor: pointer;
      }
    }

    .backdrop {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(0, 0, 0, 0.5);
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.3s ease;
      z-index: 20;
    }

    .backdrop.active {
      opacity: 1;
      pointer-events: auto;
    }

    .info-card {
      position: fixed;
      color: #333;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%) scale(0.9);
      width: 330px;
      height: 300px;
      background-color: white;
      padding: 16px;
      opacity: 0;
      pointer-events: none;
      transition: all 1s ease;
      z-index: 100;

      h2 {
        font-size: 18px;
        font-weight: 500;
      }
      p {
        margin-bottom: 16px;
        font-size: 12px;
      }

      button {
        margin-top: 10px;
        padding: 8px 24px;
        background-color: #00668a;
        outline: none;
        border: none;
        color: white;
        transition: background-color 0.2s;
        cursor: pointer;
      }
    }

    .is-show {
      display: block;
      opacity: 1;
      transform: translate(-50%, -50%) scale(1.1);
      pointer-events: auto;
    }
  }

  .text {
    width: 100%;
    height: 40px;

    text-align: center;
    font-size: 16px;
    line-height: 24px;
    background-color: rgb(0, 78, 113);
    padding: 8px;
  }

  .weather-today {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20px;
    margin-top: 24px;
  }

  hr {
    width: 100%;
    height: 0;
    border-bottom: 1px rgba(255, 255, 255, 0.1);
    margin-top: 24px;
  }

  .weather-container {
    width: 960px;
    background: rgb(0, 78, 113);
    padding: 0 48px;
    padding-top: 40px;
    margin-top: 8px;
    border-radius: 4px;

    .weather-content {
      .weather-days {
        display: flex;
        gap: 24px;

        .weather-day {
          display: flex;
          flex-direction: column;
          flex: 1;
          text-align: center;
          gap: 16px;

          span {
            display: block;
          }
        }
      }

      .weather-chart {
        height: 160px;
        margin-top: 20px;
      }
    }
  }
}
</style>
